// 导入数据库模块
const { result } = require('@hapi/joi/lib/base');
const db = require('../DB/index');

// 查询所有考勤组信息包括所属区域名称
exports.getAttendance = (req, res) => {
	const sql = `SELECT attendance.id,attendance.name,attendance.town_id,town.town_name,attendance.startWork,attendance.endWork,attendance.attendanceTime,attendance.intervalTime  
                FROM attendance ,town
                WHERE attendance.town_id = town.id`;
	db.query(sql, (err, result) => {
		if (err) return res.cc(err);
		res.send({
			status: 0,
			message: '获取信息成功',
			data: result
		});
	});
};

// 根据区域id获取考勤组信息
exports.idToAttendance = (req, res) => {
	const obj = req.body;
	const sql = `SELECT * FROM attendance WHERE town_id = ${obj.id}`;
	db.query(sql, (err, result) => {
		if (err) return res.cc(err);
		res.send({
			status: 0,
			message: '获取用户成功',
			data: result
		});
	});
};

// 根据id获取考勤组信息
exports.idAttendance = (req, res) => {
	const obj = req.body;
	const sql = `SELECT * FROM attendance WHERE id = ${obj.attendance_id}`;
	db.query(sql, (err, result) => {
		if (err) return res.cc(err);
		if (result.length === 0) return res.cc('查询错误');
		res.send({
			status: 0,
			message: '查询成功',
			data: result[0]
		});
	});
};

//新增考勤组信息
exports.addAttendance = (req, res) => {
	const obj = req.body;
	const sql = `INSERT INTO attendance SET ?`;
	db.query(
		sql,
		{
			name: obj.name,
			town_id: obj.town_id,
			attendanceTime: obj.attendanceTime,
			startWork: obj.startWork,
			endWork: obj.endWork,
			intervalTime: obj.intervalTime
		},
		(err, result) => {
			// 判断sql语句是否执行成功
			if (err) return res.cc(err);
			// 判断影响函数是否为1
			if (result.affectedRows !== 1) return res.cc('新增失败！');
			res.cc('新增成功', 0);
		}
	);
};

// 修改考勤组信息
exports.updateAttendance = (req, res) => {
	const obj = req.body;
	const startdate = new Date(obj.startWork);
	const enddate = new Date(obj.endWork);
	const start = zero(startdate.getHours()) + ':' + zero(startdate.getMinutes()) + ':' + zero(startdate.getSeconds());
	const end = zero(enddate.getHours()) + ':' + zero(enddate.getMinutes()) + ':' + zero(enddate.getSeconds());
	const sql = `UPDATE attendance SET name = '${obj.name}', town_id = ${obj.town_id},attendanceTime ='${obj.attendanceTime}',
    startWork = '${start}',endWork = '${end}',intervalTime = ${obj.intervalTime} WHERE id = ${obj.id}`;
	db.query(sql, (err, result) => {
		if (err) return res.cc(err);
		if (result.affectedRows !== 1) return res.cc('修改失败');
		res.cc('修改成功', 0);
	});
};
// 删除区域
exports.delAttendance = (req, res) => {
	const obj = req.body;
	const sql = `DELETE FROM attendance WHERE id = ${obj.id}`;
	db.query(sql, (err, result) => {
		if (err) return res.cc(err);
		if (result.affectedRows !== 1) return res.cc('删除失败');
		res.cc('删除成功', 0);
	});
};

// 查看上班状态
exports.stateWork = (req,res)=>{
	const obj = req.body
	const day = new Date().getDate()
	const sql = `SELECT * FROM attendanceData where user_id = ${obj.id}`
	db.query(sql,(err,result)=>{
		if (err) return res.cc(err);
		if (result.length === 0) {
			const sqlStr = `INSERT INTO attendanceData(attendance,end,start,day,user_id) VALUES(1,0,0,${day},${obj.id})`
			db.query(sqlStr,(err,result)=>{
				if(err) return res.cc(err)
				if(result.affectedRows !== 1) return res.cc('添加失败')
			})
		};
		res.send({
			status: 0,
			message: '查询成功',
			data: result[0]
		});
	})
}

// 上班打卡
exports.startWork = (req,res)=>{
	const obj = req.body
	sql = `UPDATE attendanceData SET start = 1 where user_id = ${obj.id}`
	db.query(sql,(err,result)=>{
		if (err) return res.cc(err);
		if (result.affectedRows !== 1) return res.cc('修改失败');
		res.cc('修改成功', 0);
	})
}

// 下班打卡
exports.endWork = (req,res)=>{
	const obj = req.body
	const day = new Date().getDate()
	// 下班打卡时：
	sql = `UPDATE attendanceData SET end = 1 ,attendance = 0,day = ${day} where user_id = ${obj.id}`
	db.query(sql,(err,result)=>{
		if (err) return res.cc(err);
		if (result.affectedRows !== 1) return res.cc('修改失败');
		res.cc('修改成功', 0);
	})
}

// 重置上班状态
exports.resetWork = (req,res)=>{
	const obj = req.body
	const sql = `SELECT attendance,day FROM attendanceData WHERE user_id = ${obj.id}`
	db.query(sql,(err,result)=>{
		if(err) return res.cc(err)
		if(result.length !== 1) return res.cc('查询失败')
		const day = new Date().getDate()
		if(result[0].attendance === 0 && result[0].day !== day){
			const sql =  `UPDATE attendanceData SET start = 0,end = 0,attendance = 1 WHERE user_id = ${obj.id}`
			db.query(sql,(err,result)=>{
				if (err) return res.cc(err);
				if (result.affectedRows !== 1) return res.cc('修改失败');
				res.cc('修改成功', 0);
			})
		}else{
			res.cc('不需要修改',0)
		}

	})
}

// 添加考勤数据
exports.attendance = (req, res) => {
	const obj = req.body;
	const date = new Date();
	// 需要用户id 当前年份 当前月份， 考勤制度
	const year = date.getFullYear();
	const month = zero(date.getMonth() + 1);
	// 查看考勤表中，该用户是否当月有数据,没有则创建当月数据
	const sql = `SELECT * FROM attendance_user WHERE user_id = ${obj.user_id} AND year = ${year} AND month = ${parseInt(
		month
	)}`;
	db.query(sql, (err, result) => {
		if (err) return res.cc(err);
		if (result.length === 0) {
			const sql = `INSERT INTO attendance_user SET ?`;
			const days = getDays();
			db.query(
				sql,
				{
					user_id: obj.user_id,
					year: parseInt(year),
					month: parseInt(month),
					normal: 0,
					late: 0,
					early: 0,
					field: 0,
					lack: 0,
					absenteeism: days,
					leave: 0
				},
				(err, result) => {
					if (err) return res.cc(err);
					if (result.affectedRows !== 1) return res.cc('添加失败');
				}
			);
		}
        let strSql = 'UPDATE attendance_user SET ';
        switch (obj.type) {
            case 'normal':
                strSql += `normal = normal + 1,`;
                break;
            case 'late':
                strSql += `late = late + 1,`;
                break;
            case 'early':
                strSql += `early = early + 1,`;
                break;
            case 'field':
                strSql += `field = field + 1,`;
                break;
            case 'lack':
                strSql += `lack = lack + 1,`;
                break;
        }
        strSql += `absenteeism = absenteeism - 1 WHERE user_id = ${obj.user_id} AND year = ${year} AND month = ${month}`
        db.query(strSql,(err,result)=>{
            if(err) return res.cc
            if(result.affectedRows !== 1) return res.cc('修改数据失败')
            const date = getDate()
            const sqlStr = `INSERT INTO attendance_info SET ?`
            db.query(sqlStr,{
                user_id : obj.user_id,
                type: obj.type,
                date: date
            },(err,response)=>{
                if(err) return res.cc(err)
                if(response.affectedRows !== 1) return res.cc('新增数据失败')
                res.cc('考勤成功',0)
            })
        })
	});
	
};

// 补零
function zero(item) {
	if (item < 10) {
		return '0' + item;
	} else {
		return item;
	}
}

// 获取当前月份有多少天
function getDays() {
	const date = new Date();
	date.setMonth(date.getMonth() + 1);
	date.setDate(0);
	const days = date.getDate();
	return days;
}

// 获取当前日期
function getDate(){
    const date = new Date()
    const yyyy = date.getFullYear()
    const MM = zero(date.getMonth() + 1)
    const dd = zero(date.getDate())
    return yyyy + '-' + MM + '-'+dd
}